const { verifyToken } = require('../utils/token');
const { SimpleData } = require('./returnDataFormat');

module.exports.verifyUser = async function (req, res, next) {
  const token = req.headers.authorization;
  if (
    req.path == '/login' ||
    req.path == '/register' ||
    req.path == '/findOneUser'
  ) {
    return next();
  }
  if (!token) {
    return res.send({ ...SimpleData(500, 'token不存在或错误'), token: false });
  } else {
    try {
      verifyToken(token);
      next();
    } catch (error) {
      res.send(SimpleData(502, 'token验证错误'));
    }
  }
};

module.exports.verifyAdmin = async (req, res, next) => {
  const token = req.headers.authorization;
  if (req.path == '/login' || req.path == '/register') {
    return next();
  }
  if (!token) {
    return res.send({ ...SimpleData(500, 'token不存在或错误'), token: false });
  } else {
    try {
      let { data: user } = await verifyToken(token);
      if (user.userLevel > 1) {
        next();
      } else {
        res.send(SimpleData(503, '用户非管理员'));
      }
    } catch (error) {
      res.send(SimpleData(502, 'token验证错误'));
    }
  }
};

module.exports.verifyTopic = async function (req, res, next) {
  const token = req.headers.authorization;
  if (
    req.path == '/getTopicById' ||
    req.path == '/getAllTopic' ||
    req.path == '/getPagingTopic' ||
    req.path == '/getTopicTypes'
  ) {
    return next();
  }
  if (!token) {
    return res.send({ ...SimpleData(500, 'token不存在或错误'), token: false });
  } else {
    try {
      verifyToken(token);
      next();
    } catch (error) {
      res.send(SimpleData(502, 'token验证错误'));
    }
  }
};
